package com.example.fiction.ui.activity.reader;

import android.app.Activity;
import android.app.Application;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.SeekBar;

import com.example.fiction.R;
import com.example.fiction.base.BaseRecyclerViewAdapter;
import com.example.fiction.interfacz.IDirectory;
import com.example.fiction.ui.activity.reader.entry.ChapterContentBean;
import com.example.fiction.ui.activity.reader.entry.ChapterItemBean;
import com.example.fiction.ui.activity.reader.server.LocalServer;
import com.example.fiction.utils.ScreenUtils;
import com.example.fiction.view.ReaderBrightnessView;
import com.example.fiction.view.ReaderFontView;
import com.example.fiction.view.ReaderMenuView;
import com.glong.reader.TurnStatus;
import com.glong.reader.widget.EffectOfCover;
import com.glong.reader.widget.EffectOfRealBothWay;
import com.glong.reader.widget.EffectOfRealOneWay;
import com.glong.reader.widget.EffectOfSlide;
import com.glong.reader.widget.OnReaderWatcherListener;
import com.glong.reader.widget.ReaderResolve;
import com.glong.reader.widget.ReaderView;

import java.util.List;

import me.goldze.mvvmhabit.base.BaseViewModel;

/**
 * auth: 姚鸿杰
 * time: 2019/3/24 0:36
 **/
public class ReaderViewModel extends BaseViewModel {

    private static final int FONT_SIZE_BIG = 70;
    private static final int FONT_SIZE_SMALL = 50;

    public ReaderViewModel(@NonNull Application application) {
        super(application);
        mApplication = application;
    }

    public void setActivity(Activity activity) {
        this.activity = activity;
    }

    //打开目录
    public View.OnClickListener openChapter = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mDrawerLayout.openDrawer(mNavigation);
            readerMenu.dismiss();
        }
    };
    //上一章
    public View.OnClickListener preChapter = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mReaderManager.toPrevChapter(0);
            mReaderView.invalidateBothPage();   //刷新
        }
    };
    //下一章
    public View.OnClickListener nextChapter = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mReaderManager.toNextChapter(0);
            mReaderView.invalidateBothPage();   //刷新
        }
    };

    //字体模块
    public void openChapter(final ReaderFontView readerFont, View v) {
        this.readerFont = readerFont;
        v.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                readerFont.show();
                readerMenu.dismiss();
            }
        });
    }

    //加大字体
    public View.OnClickListener biggerFont = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            int size = mReaderView.getTextSize();
            mReaderView.setTextSize(size + 1 > FONT_SIZE_BIG ? FONT_SIZE_BIG : size + 1);
        }
    };

    //缩小字体
    public View.OnClickListener smallerFont = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            int size = mReaderView.getTextSize();
            mReaderView.setTextSize(size - 1 < FONT_SIZE_SMALL ? FONT_SIZE_SMALL : size - 1);
        }
    };

    //翻页模式
    public void setEffect(View v, final int index) {
        v.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (index) {
                    case 0:
                        mReaderView.setEffect(new EffectOfCover(mApplication));
                        break;
                    case 1:
                        mReaderView.setEffect(new EffectOfSlide(mApplication));
                        break;
                    case 2:
                        mReaderView.setEffect(new EffectOfRealOneWay(mApplication));
                        break;
                    case 3:
                        mReaderView.setEffect(new EffectOfRealBothWay(mApplication));
                        break;
                }
                readerFont.dismiss();
            }
        });
    }

    //亮度模块
    public void openBtightness(final ReaderBrightnessView brightness, View v) {
        v.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                brightness.show();
                readerMenu.dismiss();
            }
        });
    }

    //调节亮度
    public SeekBar.OnSeekBarChangeListener regulationLight = new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            ScreenUtils.changeAppBrightness(activity, progress);
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {

        }
    };

    //系统亮度
    public View.OnClickListener setSystemLight = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            ScreenUtils.changeAppBrightness(activity, -1);
        }
    };

    //背景切换
    public void switchBackground(View v, final int index) {
        v.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (index) {
                    case 0:
                        mReaderView.setBackground(mApplication.getResources().getDrawable(R.color.reader_bg_0));
                        break;
                    case 1:
                        mReaderView.setBackground(mApplication.getResources().getDrawable(R.color.reader_bg_1));
                        break;
                    case 2:
                        mReaderView.setBackground(mApplication.getResources().getDrawable(R.color.reader_bg_2));
                        break;
                    case 3:
                        mReaderView.setBackground(mApplication.getResources().getDrawable(R.color.reader_bg_3));
                        break;
                }
            }
        });
    }

    private Application mApplication;
    private BaseRecyclerViewAdapter<ChapterItemBean> directory;
    private ReaderView mReaderView;
    private DrawerLayout mDrawerLayout;
    private ReaderView.ReaderManager mReaderManager;
    private NavigationView mNavigation;
    private ReaderMenuView readerMenu;
    private SeekBar mSeekBar;
    private ReaderResolve resolve;
    private ReaderFontView readerFont;
    private Activity activity;

    private ReaderView.Adapter<ChapterItemBean, ChapterContentBean> mAdapter = new ReaderView.Adapter<ChapterItemBean, ChapterContentBean>() {
        /**
         * 这个方法运行在子线程中，同步返回章节内容
         */
        @Override
        public ChapterContentBean downLoad(ChapterItemBean chapterItemBean) {
            return LocalServer.syncDownloadContent(chapterItemBean);
        }

        @Override
        public String obtainCacheKey(ChapterItemBean chapterItemBean) {
            return chapterItemBean.getChapterId();
        }

        @Override
        public String obtainChapterName(ChapterItemBean chapterItemBean) {
            return chapterItemBean.getChapterName();
        }

        @Override
        public String obtainChapterContent(ChapterContentBean chapterContentBean) {
            return chapterContentBean.getChapterContent();
        }
    };

    //初始化阅读器
    public void setReaderView(ReaderView readerView) {
        this.mReaderView = readerView;
        mReaderManager = new ReaderView.ReaderManager();
        mReaderManager.setOnReaderWatcherListener(onReaderWatcherListener);
        mReaderView.setReaderManager(mReaderManager);
        resolve = mReaderManager.getReaderResolve();
        mReaderView.setAdapter(mAdapter);

        int[] padding = mReaderView.getBodyTextPadding();
        padding[1] += ScreenUtils.getStatusHeight(mApplication);
        mReaderView.setBodyTextPadding(padding);
    }

    //初始化目录
    public void setReaderDirectory(RecyclerView readerDirectory, BaseRecyclerViewAdapter<ChapterItemBean> adapter) {
        directory = adapter;
        readerDirectory.setLayoutManager(new LinearLayoutManager(mApplication));
        readerDirectory.setAdapter(directory);
        directory.setItemClickListener(new IDirectory<ChapterItemBean>() {
            @Override
            public void itemClick(View v, int position, ChapterItemBean chapterItemBean) {
                mDrawerLayout.closeDrawers();   //关闭目录
                mReaderManager.toSpecifiedChapter(position, 0); //跳转到指定章节
                mReaderView.invalidateBothPage();   //刷新
            }
        });
    }

    //初始化策划栏
    public void setReaderDrawLayout(final DrawerLayout readerDrawLayout) {
        mDrawerLayout = readerDrawLayout;
        mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);// 不响应滑动打开
        // 这个订阅目的:当抽屉打开时可以滑动关闭,未打开时不能滑动打开
        mDrawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
            @Override
            public void onDrawerSlide(@NonNull View view, float v) {

            }

            @Override
            public void onDrawerOpened(@NonNull View view) {
                readerDrawLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
            }

            @Override
            public void onDrawerClosed(@NonNull View view) {
                readerDrawLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
            }

            @Override
            public void onDrawerStateChanged(int i) {
            }
        });
    }

    public void setNavigation(NavigationView navigation) {
        this.mNavigation = navigation;
        //设置目录paddding值
        this.mNavigation.setPadding(0, ScreenUtils.getStatusHeight(mApplication), 0, 0);
    }

    //初始化菜单
    public void setReaderMenu(ReaderMenuView readerMenu) {
        this.readerMenu = readerMenu;
    }

    //初始化拖动进度条
    public void setSeekBar(SeekBar seekBar) {
        this.mSeekBar = seekBar;
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                TurnStatus turnStatus = mReaderManager.toSpecifiedChapter(seekBar.getProgress() == 0
                        ? 0 : seekBar.getProgress() - 1, 0);
                if (turnStatus == TurnStatus.LOAD_SUCCESS)
                    mReaderView.invalidateBothPage();   //刷新
            }
        });
    }

    public void initData(String bookId) {

        LocalServer.getChapterList(bookId, new LocalServer.OnResponseCallback() {
            @Override
            public void onSuccess(List<ChapterItemBean> chapters) {
                mAdapter.setChapterList(chapters);  //添加章节目录
                mAdapter.notifyDataSetChanged();    //更新
                directory.setLists(chapters);
                directory.notifyDataSetChanged();

                mSeekBar.setMax(resolve.getChapterSum());   //设置最大值
                mSeekBar.setProgress(resolve.getChapterIndex());    //设置当前章节
            }

            @Override
            public void onError(Exception e) {

            }
        });
    }

    private OnReaderWatcherListener onReaderWatcherListener = new OnReaderWatcherListener() {
        /**
         * 页码发生了变化
         * @param pageIndex 第pageIndex页（从第0页开始）
         */
        @Override
        public void onPageChanged(int pageIndex) {
            //todo 以后做百分比
//                float a = (resolve.getChapterSum() * resolve.getPageSum());  //总页数
//                float b = resolve.getChapterIndex() * resolve.getPageSum() + pageIndex+1;  //已读页数

//                SharedPreferences.Editor editor = getApplication().getSharedPreferences("user", Context.MODE_PRIVATE).edit();
//                editor.putInt("index", resolve.getCharIndex());
//                editor.apply();
        }

        /**
         * 章节发生了变化
         * @param chapterIndex 跳转到了第chapterIndex章
         * @param pageIndex    跳转到了这章的第pageIndex页（从第0页开始）
         */
        @Override
        public void onChapterChanged(int chapterIndex, int pageIndex) {

        }

        /**
         * 开始下载当前所需章节时调用（方便弹出提示等等）
         * 当下载缓存时不会回调
         * @param chapterIndex 章节索引
         */
        @Override
        public void onChapterDownloadStart(int chapterIndex) {

        }

        /**
         * 当前所需章节下载成功后回调
         * 仅下载缓存时不会回调
         * @param chapterIndex 章节索引
         */
        @Override
        public void onChapterDownloadSuccess(int chapterIndex) {

        }

        /**
         * 当前所需章节下载失败后回调
         * 仅下载缓存时不会回调
         * @param chapterIndex 章节索引
         */
        @Override
        public void onChapterDownloadError(int chapterIndex) {

        }
    };

}
